package com.earthchen.decoder;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.util.CharsetUtil;


/**
 * 启动类
 *
 * @author: EarthChen
 * @date: 2018/04/26
 */
public class Main {

    /**
     * 改为127.0.0.1表示只能本机访问
     * 0.0.0.0 或外网ip表示均能访问
     */
    private static final String IP = "0.0.0.0";
    private static final int PORT = 5050;

    //默认
    private static final int BIZGROUPSIZE = Runtime.getRuntime().availableProcessors() * 2;

    private static final int BIZTHREADSIZE = 4;

    private static final EventLoopGroup bossGroup = new NioEventLoopGroup(BIZGROUPSIZE);
    private static final EventLoopGroup workerGroup = new NioEventLoopGroup(BIZTHREADSIZE);

    private static void run() throws Exception {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup);
        b.channel(NioServerSocketChannel.class);
        b.childHandler(new ChannelInitializer() {
            @Override
            protected void initChannel(Channel channel) throws Exception {
                ChannelPipeline pipeline = channel.pipeline();
//                pipeline.addLast(new LengthFieldBasedFrameDecoder(10240,0,4,0,4));
//                pipeline.addLast(new LengthFieldPrepender(4));
//
//                pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
//                pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));

//                pipeline.addLast(new ToIntegerDecoder());
                pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
                pipeline.addLast(new StringToIntegerDecoder());
                pipeline.addLast(new ServerHandler());
            }

        });

        b.bind(IP, PORT).sync();
        System.out.println("TCP服务器已启动");
    }

    protected static void shutdown() {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }

    public static void main(String[] args) throws Exception {
        Main.run();
//      TcpServer.shutdown();
    }
}



